package com.ojoin.trade.t0loan_core.web.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common_core.web.domain.AccountDetail;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantuserExceptionorderBaseService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.common.web.controller.SimpleBaseController;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Result.Status;
import com.ojoin.trade.common.web.service.IRSAService;
import com.ojoin.trade.common_core.utils.TradeUtils;
import com.ojoin.trade.common_core.web.service.AccountBaseService;
import com.ojoin.trade.t0loan_core.web.domain.BankCard;

@Controller
@RequestMapping("/account")
public class AccountController  extends SimpleBaseController {

	private static Logger log = LoggerFactory
			.getLogger(AccountController.class);

	@Autowired
	private AccountBaseService accountbaseservice;

	@Autowired
	private TbMerchantInfoBaseService minfoservice;
	
	@Autowired
	private IRSAService rsaSrv;

    @Autowired
    private TbMerchantuserExceptionorderBaseService tbMerchantuserExceptionorderBaseService;
	
	public AccountBaseService getAccountbaseservice() {
		return accountbaseservice;
	}

	@ResponseBody
	@RequestMapping(value = "/queryBaseAccountBalance", method = RequestMethod.POST)
	public Result queryBaseAccountBalance(HttpServletRequest request) {
      //  return new Result(Status.OK,"[{\"balance\":12234566666}]");  //TODO账户余额
		String mhtNo = TradeUtils.getMhtNo(request);
		try {
			List list = getAccountbaseservice().queryBaseAccountBalance(mhtNo, IConstDef.ACCTYPE_BASE);
			if (CommonUtils.isSuccess(list)) {
				Map<String, String> data = (Map) list.get(1);
				String mhtData = "";
				mhtData = data.get("mhtData");
				if (StringUtils.isEmpty(mhtData)) {
					mhtData = data.get("accData");
				}
				return new Result(Status.OK, mhtData);
			} else {
				return CommonUtils.buildError(list);
			}
		} catch (Exception e) {
			log.error("查询商户账户余额失败", e);
			return new Result(Status.ERROR, "查询商户账户余额失败");
		}
	}
    @ResponseBody
    @RequestMapping(value="/queryDrawfee",method = RequestMethod.POST)
    public Result queryDrawfee(HttpServletRequest request,String amount){

        try{
            BigDecimal  amountdecimal=new BigDecimal(amount);
        }catch (Exception e){
            return new Result(Status.ERROR,"输入的金额格式不对");
        }
        try{
            int fee=accountbaseservice.queryFeeForDraw(amount);
            return new Result(Status.OK,fee);
        }catch (Exception e){
            LogUtils.error(log,e,"计算提现手续费出错");
            return new Result(Status.ERROR,"系统出错");
        }
    }
	@ResponseBody
	@RequestMapping(value="/drawAccountBalance",method=RequestMethod.POST)
	public Result drawAccountBalance(HttpServletRequest request,String payPasswd,String cardId,String amount){
        if (StringUtils.isEmpty(amount)) {
            return new Result(Status.ERROR, "请输入提现金额");
        }

		CommonUtils.checkRSAExpired(request);

        try{
            BigDecimal  amountdecimal=new BigDecimal(amount);
        }catch (Exception e){
            return new Result(Status.ERROR,"输入的金额格式不对");
        }
        String mhtNo = TradeUtils.getMhtNo(request);
		if(StringUtils.isEmpty(payPasswd)){
			return new Result(Status.ERROR,"请输入支付密码");
		}
		if (StringUtils.isEmpty(cardId)) {
			return new Result(Status.ERROR, "请选择一张卡");
		}

		
		//登录现在支付
		payPasswd = rsaSrv.decryptStringByJs(payPasswd);

		BigDecimal amountm100 = new BigDecimal(amount).multiply(new BigDecimal(100));
		long intAmount = amountm100.longValue();
		
		String memo = TimeUtils.getCurTime() + "提现," + "金额" + amount + "元";
		try {
           boolean isfrezz= tbMerchantuserExceptionorderBaseService.isFreezeByJoinuserID(TradeUtils.getJoinId());
           if(isfrezz){
               throw  new BusinessException("账户已被锁定，请联系保理公司");
           }
			getAccountbaseservice().drawAccountBalance(mhtNo,
					payPasswd, cardId, CommonUtils.getString(intAmount), memo);
            return new Result(Status.OK, "提现成功");
		} catch (Exception e) {
            if(e instanceof BusinessException){
                return new Result(Status.ERROR,e.getMessage());
            }
			log.error("取现失败", e);
			return new Result(Status.ERROR, "取现失败");
		}
	}

	@ResponseBody
	@RequestMapping(value = "/queryAccountChangeDetail", method = RequestMethod.GET)
	public Result queryAccountChangeDetail(@PageableDefault Pageable pageable,
			HttpServletRequest request, String beginDate, String endDate,
			String operation) {

		String mhtNo = TradeUtils.getMhtNo(request);
		String accType = IConstDef.ACCTYPE_BOTH;// Both
		Map<String, String> queryDataMap = new HashMap<String, String>();
		queryDataMap.put("begindate", beginDate);
		queryDataMap.put("enddate", endDate);
		queryDataMap.put("operation", operation);

		String queryData = JSONUtils.toJSONString(queryDataMap);

		try {
			List list = getAccountbaseservice().queryAccountChangeDetail(mhtNo,
					accType, String.valueOf(pageable.getPageNumber()),
					String.valueOf(pageable.getPageSize()), queryData);
			if (CommonUtils.isSuccess(list)) {
				Map<String, String> data = (Map) list.get(1);
				String tradeData = data.get("tradeData");
				if (StringUtils.isEmpty(tradeData)) {
					return new Result(Status.OK, null);
				}
				Map tradeDataMap = JSONUtils.parseObject(tradeData, java.util.Map.class);
				Integer records = (Integer) tradeDataMap.get("records");
				List<Map> transData = (List<Map>) tradeDataMap.get("data");
//				AccountDetail[] transData = JSONUtils.parseObject((String)tradeDataMap.get("data"), AccountDetail[].class);
//				List transData = JSONUtils.parseObject(tradeDataMap.get("data"), java.util.List.class);
				if (transData == null || transData.size() == 0) {
					return new Result(Status.OK, null);
				}
				updateMhtName(transData);
				Map<String, Object> ret=new HashMap<String, Object>();
				ret.put("transData", transData);
				ret.put("records", records.toString());
				return new Result(Status.OK, ret);
			} else {
				return CommonUtils.buildError(list);
			}
		} catch (Exception e) {
			log.error("查询账户变动记录失败", e);
			return new Result(Status.ERROR, "查询账户变动记录失败");
		}

	
		
	}

	private void updateMhtName(List<Map> transData) {
		if (transData == null || transData.size() == 0)
			return;
		
		for(Map account : transData) {
			TbMerchantInfo infovo = minfoservice.queryInfoByMhtno((String) account.get("mhtNoFrom"));
			account.put("mhtNoFromName", infovo != null ? infovo.getMchName() : null);
		}
		
	}
}
